package gamecfg

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"sort"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/xrjson"
)

var lvMap = make(map[uint64]*LvCfg)
var lvArray = make([]*LvCfg, common.Zero)

func initLv() {
	xrjson.RegLoadJsonHandler("lv.json", loadLv)
}

type ByLv []*LvCfg

func (a ByLv) Len() int {
	return len(a)
}

// 升序
func (a ByLv) Less(i, j int) bool {
	return a[i].Lv < a[j].Lv
}
func (a ByLv) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

// ItemSourceCfg 物品来源表
type LvCfg struct {
	Lv  uint64 `json:"lv"`
	Exp uint64 `json:"exp"`
}

func loadLv(jsonData string) {
	err := json.Unmarshal([]byte(jsonData), &lvMap)
	if err != nil {
		panic(fmt.Errorf("%v 文件加载错误 %v", jsonData, err))
	}
	for _, item := range lvMap {
		lvArray = append(lvArray, item)
	}
	sort.Sort(ByLv(lvArray))
	glog.Warningf(gctx.New(), "%s数据加载成功,长度:%v", jsonData, len(lvMap))
}

func GetLvs() []*LvCfg {
	return lvArray
}

func GetMaxLv() *LvCfg {
	return lvArray[len(lvArray)-1]
}
func GetLvById(lv uint64) *LvCfg {
	item, ok := lvMap[lv]
	if !ok {
		return nil
	}
	return item
}
